package com.ff.sca.common.aoplog;

import com.alibaba.fastjson.JSONObject;
import com.ff.sca.admin.service.RedisService;
import com.ff.sca.common.codeenum.OperateType;
import com.ff.sca.common.util.CharUtil;
import com.ff.sca.common.util.IpUtil;
import com.ff.sca.common.util.JWT;
import com.ff.sca.suser.entity.ScaSysUser;
import com.ff.sca.syslog.entity.ScaSysMangerLog;
import com.ff.sca.syslog.service.IScaSysMangerLogService;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.CodeSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by zhangmy on 2017/7/25.
 */
@Aspect
@Component
public class WebLogAspect {
    @Autowired
    private IScaSysMangerLogService sysMangerLogService;
    @Autowired
    private RedisService redisService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 获取@controllerLog 注解上信息
     *
     * @param joinPoint
     * @return map
     * @throws Exception
     */
    public static Map<String, Object> getControllerAnnotationValue(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        Map<String, Object> map = new HashMap<>();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] classes = method.getParameterTypes();
                if (classes.length == arguments.length) {
                    //取入参数据
                    String description = method.getAnnotation(ControllerLog.class).description();
                    String module = method.getAnnotation(ControllerLog.class).module();
                    String opType = method.getAnnotation(ControllerLog.class).opType().name();
                    map.put("module", module);
                    map.put("opType", opType);
                    map.put("description", description);
                    break;
                }
            }
        }
        return map;
    }


    /**
     * 定义一个切入点.
     * ("execution(public * com.kfit.*.web..*.*(..))")
     * 解释下：
     * 第一个 * 代表任意修饰符及任意返回值.
     * 第二个 * 任意包名
     * 第三个 * 代表任意方法.
     * 第四个 * 定义在web包或者子包
     * 第五个 * 任意方法
     * .. 匹配任意数量的参数.
     */
    @Pointcut("execution(public * com.ff.sca.*.controller..*.*(..)) && @annotation(com.ff.sca.common.aoplog.ControllerLog)")
    public void webLog() {
    }


    @Around("webLog()")
    public Object round(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String url = request.getRequestURI();
        String userIp = IpUtil.getIpAddr(request);
        ScaSysUser user = JWT.unsign(redisService.getAppCache("manager_token_" + userIp), ScaSysUser.class);
        //入参 value
        Object[] args = joinPoint.getArgs();
        //入参名称
        String[] paramNames = ((CodeSignature) joinPoint.getSignature()).getParameterNames();
        Map<String, Object> params = new HashMap<>();
        //获取所有参数对象
        for (int i = 0; i < args.length; i++) {
            if (null != args[i]) {
                if (args[i] instanceof BindingResult) {
                    params.put(paramNames[i], "bindingResult");
                } else {
                    //对记录参数做处理
                    if (!(paramNames[i].equals("request") || paramNames[i].equals("loginPassword"))) {
                        params.put(paramNames[i], args[i]);
                    }
                }
            } else {
                params.put(paramNames[i], "");
            }
        }
        Map<String, Object> values = getControllerAnnotationValue(joinPoint);
        String description = values.get("description").toString();
        String opType = values.get("opType").toString();
        String module = values.get("module").toString();
        //切面返回值
        Object returnValue = joinPoint.proceed();
        ScaSysMangerLog log = new ScaSysMangerLog();
        log.setIp(userIp);
        log.setDescription(description);
        log.setParams(params.toString());
        if (user != null) {
            log.setUserId(user.getId());
            log.setUserName(user.getUserName());
            log.setMobile(user.getMobile());
        }
        log.setOperateModule(module);
        log.setOperateType(opType);
        log.setUrl(url);
        log.setCreateTime(new Date());
        sysMangerLogService.insert(log);
//        operateLog.setRecordId(primaryKeyValue == null ? null : Long.parseLong(primaryKeyValue.toString()));
        return returnValue;
    }


    @AfterReturning("webLog()")
    public void doAfterReturning(JoinPoint joinPoint) {
        // 处理完请求，返回内容
        logger.info("WebLogAspect.doAfterReturning()");
    }


}
